//////////////////////////////////////////////////////////////////////////////////////////////////////
// 项目名   : ThreadManagement
// 文件名   : Joining_Thread.h
// 作者     : Aiye
// 日期     : 2025/9/17 19:21
// 邮箱     : 2878548868@qq.com
// 摘要     : 
//////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef THREADMANAGEMENT_JOINING_THREAD_H
#define THREADMANAGEMENT_JOINING_THREAD_H
#include <thread>

/**
 * @brief jthread模拟
 */
class Joining_Thread
{
public:
    Joining_Thread() noexcept = default;

    /**
     * @brief 构造函数，使用可调用对象和参数创建线程
     * @tparam Callable 可调用对象
     * @tparam Args 可调用对象类型参数
     * @param func 可调用对象
     * @param args 可调用对象的参数
     */
    template<typename Callable , typename ... Args>
    explicit Joining_Thread(Callable&& func , Args&& ... args)
        :_t(std::forward<Callable>(func) , std::forward<Args>(args)...)
    {}

    Joining_Thread(const Joining_Thread& other) = delete;
    Joining_Thread& operator=(const Joining_Thread& other) = delete;

    Joining_Thread(Joining_Thread&& other) noexcept
        : _t(std::move(other._t))
    {}

    Joining_Thread& operator=(Joining_Thread&& other) noexcept
    {
        if (_t.joinable())
        {
            _t.join();
        }
        _t = std::move(other._t);
        return *this;
    }

    ~Joining_Thread() noexcept
    {
        if (_t.joinable())
        {
            _t.join();
        }
    }

public:
    /**
     * @brief 交换你两个线程的所有权
     * @param other
     */
    void swap(Joining_Thread& other) noexcept
    {
        _t.swap(other._t);
    }

    /**
     * @brief 获取线程id
     * @return 线程id
     */
    [[nodiscard]] auto get_id() const noexcept
    {
        return _t.get_id();
    }

    [[nodiscard]] bool joinable() const
    {
        return _t.joinable();
    }

    void join()
    {
        _t.join();
    }

    void detach()
    {
        _t.detach();
    }

    auto& as_thread()
    {
        return _t;
    }

    const auto& as_thread() const noexcept
    {
        return _t;
    }

private:
    std::thread _t;     // 线程
};

#endif //THREADMANAGEMENT_JOINING_THREAD_H